<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" append-to-body width="992px">
		<el-form ref="form" size="medium" :model="formData" :rules="formRules" label-width="84px" class="enum_form_wrapper">
			<el-form-item label="问题标题" prop="ask">
				<el-input v-model="formData.ask"></el-input>
			</el-form-item>
			<el-form-item label="问题答案" prop="answer">
				<quill-editor v-model="formData.answer"></quill-editor>
			</el-form-item>
			<el-form-item label="是否展示">
				<el-switch v-model="formData.isShow" active-value="1" inactive-value="2"></el-switch>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitForm">{{ dialogType }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import { addedTbQa, updateTbQa } from '@/api/system/tbQa';
export default {
	props: {
		value: { type: Boolean, default: false },
		activeType: { type: String, default: '1' },
		data: { type: Object, default: () => {} }
	},
	data() {
		return {
			visible: this.value,
			formData: {},
			formRules: {
				ask: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
				answer: [{ required: true, message: '请输入回答描述', trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: {
		addOrEdit() {
			return Object.keys(this.data).length === 0;
		},
		dialogType() {
			return this.addOrEdit ? '新增' : '修改';
		},
		dialogTitle() {
			return `${this.dialogType}问题`;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.$nextTick(() => {
				this.$refs['form'].resetFields();
				this.formData = this.addOrEdit ? {} : { ...this.data };
			});
		}
	},
	methods: {
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				await this.submitFormRequest();
				this.btnLoading = false;
			});
		},
		//添加/修改请求
		async submitFormRequest() {
			let params = { ...this.formData };
			let requestFun = eval(this.addOrEdit ? addedTbQa : updateTbQa);
			let result = await requestFun(params).then((res) => res.data);
			if (result.code === '0') {
				this.$emit('refresh');
				this.visible = false;
				this.$showCustomMessage('success', `${this.dialogTitle}成功`);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.enum_form_wrapper {
	flex: 1;
	padding: 10px 10px 0 0;
	overflow: hidden;
}
</style>
